<template>
  <el-upload
    class="avatar-uploader"
    action="/file/fileUpload"
    :data="params"
    :show-file-list="false"
    :on-success="handleSuccess"
    accept="image/*"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>
<script>
  export default {
    data() {
      return {
        params: {}
      };
    },
    methods: {
      handleSuccess(res, file, fileList){
        if(res.status === '0'){
          const guid = res.data
          this.$emit('input', guid)
          this.$notify.success('文件：'+ file.name +'上传成功！')
        }else{
          this.$notify.error('文件：'+ file.name +'上传失败')
        }
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < this.maxFileSize;

        if (!isLt2M) {
          this.$notify.error(`上传头像图片大小不能超过 ${this.maxFileSize}MB!`);
        }
        return isLt2M;
      }
    },
    computed: {
      imageUrl(){
        if(this.value){
          return '/file/getFile/'+ this.value
        }
        return ''
      }
    },
    props: {
      value: {
        type: String,
        required: true
      },
      model: {
        type: String,
        default: ''
      },
      entity: {
        type: String,
        default: ''
      },
      entityId: {
        type: String,
        default: ''
      },
      accept: {
        type: String,
        default: ''
      },
      // 文件上传最大小值
      maxFileSize: {
        type: Number,
        default: 2
      }
    },
    created() {
      this.params = {
        'upEntity': this.entity,
        'upEntityId': this.entityId,
        'upModel': this.model
      }
    }
  }
</script>
